package database

import (
	"fmt"
	"log"
	"rego-top/config"
	"rego-top/models"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

// InitDB 初始化数据库连接
func InitDB(cfg *config.Config) error {
	dbCfg := cfg.Database
	
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbCfg.User,
		dbCfg.Password,
		dbCfg.Host,
		dbCfg.Port,
		dbCfg.DBName,
	)

	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		return fmt.Errorf("failed to connect to database: %w", err)
	}

	log.Println("Database connected successfully")

	// 自动迁移
	if err := AutoMigrate(); err != nil {
		return fmt.Errorf("failed to migrate database: %w", err)
	}

	// 初始化种子数据
	if err := SeedData(); err != nil {
		return fmt.Errorf("failed to seed data: %w", err)
	}
	
	return nil
}

// AutoMigrate 自动迁移数据库表
func AutoMigrate() error {
	return DB.AutoMigrate(
		&models.User{},
		&models.Role{},
		&models.Permission{},
		&models.UserRole{},
		&models.RolePermission{},
		&models.RefreshToken{},
	)
}

// SeedData 初始化种子数据
func SeedData() error {
	// 创建默认权限
	permissions := []models.Permission{
		{Name: "user.create", DisplayName: "创建用户", Description: "创建新用户", Resource: "user", Action: "create"},
		{Name: "user.read", DisplayName: "查看用户", Description: "查看用户信息", Resource: "user", Action: "read"},
		{Name: "user.update", DisplayName: "更新用户", Description: "更新用户信息", Resource: "user", Action: "update"},
		{Name: "user.delete", DisplayName: "删除用户", Description: "删除用户", Resource: "user", Action: "delete"},
		{Name: "role.create", DisplayName: "创建角色", Description: "创建新角色", Resource: "role", Action: "create"},
		{Name: "role.read", DisplayName: "查看角色", Description: "查看角色信息", Resource: "role", Action: "read"},
		{Name: "role.update", DisplayName: "更新角色", Description: "更新角色信息", Resource: "role", Action: "update"},
		{Name: "role.delete", DisplayName: "删除角色", Description: "删除角色", Resource: "role", Action: "delete"},
		{Name: "permission.read", DisplayName: "查看权限", Description: "查看权限信息", Resource: "permission", Action: "read"},
	}

	for _, permission := range permissions {
		var existingPermission models.Permission
		if err := DB.Where("name = ?", permission.Name).First(&existingPermission).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				if err := DB.Create(&permission).Error; err != nil {
					return err
				}
			} else {
				return err
			}
		}
	}

	// 创建默认角色
	roles := []models.Role{
		{Name: "admin", DisplayName: "管理员", Description: "系统管理员，拥有所有权限"},
		{Name: "user", DisplayName: "普通用户", Description: "普通用户，拥有基本权限"},
	}

	for _, role := range roles {
		var existingRole models.Role
		if err := DB.Where("name = ?", role.Name).First(&existingRole).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				if err := DB.Create(&role).Error; err != nil {
					return err
				}
			} else {
				return err
			}
		}
	}

	// 为管理员角色分配所有权限
	var adminRole models.Role
	if err := DB.Where("name = ?", "admin").First(&adminRole).Error; err != nil {
		return err
	}

	var allPermissions []models.Permission
	if err := DB.Find(&allPermissions).Error; err != nil {
		return err
	}

	for _, permission := range allPermissions {
		var existingRolePermission models.RolePermission
		if err := DB.Where("role_id = ? AND permission_id = ?", adminRole.ID, permission.ID).First(&existingRolePermission).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				rolePermission := models.RolePermission{
					RoleID:       adminRole.ID,
					PermissionID: permission.ID,
				}
				if err := DB.Create(&rolePermission).Error; err != nil {
					return err
				}
			} else {
				return err
			}
		}
	}

	// 为普通用户角色分配基本权限
	var userRole models.Role
	if err := DB.Where("name = ?", "user").First(&userRole).Error; err != nil {
		return err
	}

	userPermissions := []string{"user.read", "permission.read"}
	for _, permName := range userPermissions {
		var permission models.Permission
		if err := DB.Where("name = ?", permName).First(&permission).Error; err != nil {
			continue
		}

		var existingRolePermission models.RolePermission
		if err := DB.Where("role_id = ? AND permission_id = ?", userRole.ID, permission.ID).First(&existingRolePermission).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				rolePermission := models.RolePermission{
					RoleID:       userRole.ID,
					PermissionID: permission.ID,
				}
				if err := DB.Create(&rolePermission).Error; err != nil {
					return err
				}
			} else {
				return err
			}
		}
	}

	log.Println("Seed data initialized successfully")
	return nil
}